import 'package:pacsun/constants/apiConstants.dart' show ApiConstants;
import 'base/apiClient.dart';

import 'package:pacsun/model/apiResponse.dart' show ApiResponse;
import 'package:pacsun/model/SocialMediaUserModel.dart' show TikTokUserModel;

class TikTokConnect {
  final ApiClient _apiClient = ApiClient();

  Future<String> getOauth2SSO() async {
    try {
      String uri = '/api/v1/tiktok/getOauth2Link';

      // 确保请求认证链接时包含 redirect_uri
      final response = await _apiClient.get(
        uri,
        headers: ApiConstants.jsonHeaders,
        // queryParameters: {'redirect_uri': _redirectUri},
      );

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
          response.data, (data) => data as Map<String, dynamic>);

      if (apiResponse.isSuccess) {
        final _authUrl = apiResponse.data!['link'];

        if (_authUrl == null || _authUrl.isEmpty) {
          throw Exception('Received empty or null auth URL');
        }

        return _authUrl;
      } else {
        throw Exception('Failed to connect TikTok: ${apiResponse.message}');
      }
    } catch (e) {
      print('=== TikTok Auth Error ===');
      print('Error: $e');
      print('=========================');
      throw Exception('Failed to connect TikTok: $e');
    }
  }

  Future<String> exchangeCodeForOpenId(String code, String scopes) async {
    try {
      // print('code  in exchange:  ${code}');
      // print('scopes  in exchange:  ${scopes}');

      final response = await _apiClient.get(
        '/api/v1/tiktok/callback',
        queryParameters: {
          'code': code,
          'scopes': scopes,
        },
        headers: ApiConstants.jsonHeaders,
      );
      print('response:  ${response}');
      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      if (apiResponse.isSuccess) {
        return apiResponse.data!['openId'];
      } else {
        throw apiResponse.message ?? 'Failed to exchange code for token';
      }
    } catch (e) {
      throw 'Token exchange failed: $e';
    }
  }

  Future<TikTokUserModel> getUserInfo(String openId) async {
    try {
      // print('code  in exchange:  ${code}');
      // print('scopes  in exchange:  ${scopes}');

      final response = await _apiClient.get(
        '/api/v1/tiktok/getUserInfo',
        queryParameters: {'openId': openId},
        headers: ApiConstants.jsonHeaders,
      );

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      if (apiResponse.isSuccess) {
        return TikTokUserModel.fromJson(apiResponse.data!);
      } else {
        throw apiResponse.message ??
            'Failed to get user information for TikTok';
      }
    } catch (e) {
      throw 'Token exchange failed: $e';
    }
  }
}
